package com.lyf.common.api;

import com.fasterxml.jackson.annotation.JsonCreator;

import java.util.HashMap;

/**
 * 枚举了一些常用API操作码
 * TODO 需要完善
 */
public enum ResultCode implements IErrorCode {
    SUCCESS(200, "操作成功"),
    SUCCESS_200(200, "操作成功"),
    SUCCESS_0(0, "操作成功"),

    COOKIE_NOT_FOUND(99998, "cookie not found"),
    BUTT(99999, "BUTT"),

    // 不使用 500做错误
    METHOD_NOT_SUPPORTED(100001, "不支持的请求方式"),
    PARAM_VIOLATION_ERROR(100002, "参数错误，不满足校验规则"),
    PARAM_MISS_ERROR(100003, "参数错误，请求参数没传"),
    PARAM_TYPE_ERROR(100004, "参数类型不匹配"),
    PARAM_ERROR(100005, "参数错误"),
    DATE_PARSE_ERROR(100006, "日期格式错误"),
    HTTP_MESSAGE_NOT_READABLE(100007, "字段类型不正确"),
    SERVICE_BUSY(100008, "服务繁忙"),
    FAILED(100999, "操作失败"),


    VALIDATE_FAILED(404, "参数检验失败"),
    UNAUTHORIZED(401, "暂未登录或token已经过期"),
    UNAUTHORIZED_NO_HEADER_AUTHORIZATION(401, "no header:authorization in http headers"),
    UNAUTHORIZED_INVALID_AUTHORIZATION(401, "invalid authorization"),
    AUTHORIZATION_NOT_ACCEPT(406, "not accept"),
    BAD_REQUEST(400, "bad request"),


    TOO_MANY_REQUESTS(429, "Frequency limit, please try again later"),

    FORBIDDEN(403, "没有相关权限"),

    // 错误码
//    RESPONSE_CODE_ERROR(100999, "未知错误"),
    ;

    private Integer code;
    private String msg;


    private static HashMap<Integer, ResultCode> map = new HashMap<Integer, ResultCode>();

    static {
        for (ResultCode resultCode : ResultCode.values()) {
            map.put(resultCode.getCode(), resultCode);
        }
    }


    ResultCode(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @JsonCreator
    public static ResultCode fromValue(Integer code) {
        if (null == code) {
            return BUTT;
        }

        ResultCode codeEnum = map.getOrDefault(code, BUTT);
        return codeEnum;
    }


    private ResultCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }

}
